<template>
  <basic-container>
    <el-form :inline="true" :model="query" class="demo-form-inline">
      <el-row>
        <el-form-item label="项目编号:">
          <el-input v-model="query.projectCode" clearable placeholder="项目编号" size="small"></el-input>
        </el-form-item>
        <el-form-item label="项目名称:">
          <el-input v-model="query.projectName" clearable placeholder="项目名称"></el-input>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item>
          <el-button size="small" type="primary" icon="el-icon-search" @click="onSearch" :loading="loading">搜索
          </el-button>
          <el-button size="small" icon="el-icon-delete" @click="searchReset" :loading="loading">清空</el-button>
        </el-form-item>
      </el-row>
    </el-form>
    <div class="btn-operate">
      <el-button v-if="permissions.engineering_evidence_add" @click="createEvidence" type="primary" size="small" icon="el-icon-plus">
        审计查询单
      </el-button>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      highlight-current-row
      @cell-click="handleCellClick"
      style="width: 100%">
      <el-table-column label="项目编号" prop="projectCode" width="140">
      </el-table-column>
      <el-table-column label="项目名称" prop="projectName" width="270">
        <template v-slot="scope">
            <span :style="{ color: scope.row.projectProgress === 7 ? '#f16262' : '' }">
              {{ scope.row.projectName }}
              <template v-if="scope.row.projectProgress === 7">
                <div style="display: inline-block">【已终止】</div>
              </template>
            </span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="查询单状态">
        <template slot-scope="scope">
          <span v-if="scope.row.status === 0 || scope.row.status === null">新建</span>
          <span v-else-if="scope.row.status === 1">审核中</span>
          <span v-else-if="scope.row.status === 2">驳回</span>
          <span v-else-if="scope.row.status === 3">审核通过待答复</span>
          <span v-else-if="scope.row.status === 4">已答复待转交审计组</span>
          <span v-else-if="scope.row.status === 5">已转交审计组</span>
          <span v-else-if="scope.row.status === 6">已生成问题</span>
          <span v-else-if="scope.row.status === 7">已关闭</span>
          <span v-else>未知状态</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="170">
        <template slot-scope="scope">
          <el-button v-if="permissions.engineering_evidence_get" type="text" size="small" icon="el-icon-view" @click="showViewBox(scope.row)">查看</el-button>
          <el-button v-if="permissions.engineering_evidence_add && (scope.row.status < 3 && scope.row.status !== 1)" type="text" size="small" icon="el-icon-edit" @click="showEditBox(scope.row)">编辑</el-button>
          <el-button v-if="permissions.engineering_evidence_reply && scope.row.status === 3" type="text" size="small" icon="el-icon-edit" @click="showReplyBox(scope.row)">答复</el-button>
          <el-button v-if="permissions.engineering_evidence_examine && scope.row.status === 4" type="text" size="small" icon="el-icon-edit" @click="showAuditBox(scope.row)">审核</el-button>
<!--          <el-button v-if="permissions.create_dicovery && scope.row.status === 5" type="text" size="small" icon="el-icon-edit" @click="showConfirmBox(scope.row)">确认问题</el-button>-->
          <el-button v-if="scope.row.taskId" type="text" size="small" icon="el-icon-edit" @click="showTaskAuditTaskDialog(scope.row)">审批</el-button>
          <el-button v-if="scope.row.status > 0" type="text" size="small" icon="el-icon-view" @click="showTaskAuditLogDialog(scope.row)">审批日志</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 30, 40 ,50 ,100]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total">
      </el-pagination>
    </div>

    <el-dialog title="审计查询单" fullscreen custom-class="ledger" :visible.sync="formBox" :close-on-click-modal="!formBox" :append-to-body="true" :before-close="resetForm" width="1200px" top="5vh">
      <el-form ref="optForm" :model="form" label-width="90px">
      <div class="title">基本信息</div>
        <el-row>
          <el-col :span="8">
            <el-form-item label-width="100px" label="项目编号: " prop="projectCode" :rules="{required: true, message: '项目编号不能为空', trigger: ['blur', 'change']}">
              <el-input v-model="form.projectCode" placeholder="选择项目编号" @focus="showProjectDialog()" :readonly="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="100px" label="项目名称:">
              {{ form.projectName }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="110px" label="要求反馈时间:" prop="feedbackTime" :rules="{required: true, message: '反馈时间不能为空', trigger: ['blur', 'change']}">
              <el-date-picker v-model="form.feedbackTime" type="date" placeholder="选择日期"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      <div class="title">基本信息</div>
        <el-row>
          <el-col>
            <el-form-item label-width="100px" label="查询问题:" prop="auditMatter">
              <el-input v-model="form.auditMatter" placeholder="填写问题" type="textarea" :disabled="isEdit || (form.status >= 3 || form.status === 1)"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm" size="small" icon="el-icon-close">关闭</el-button>
        <el-button v-if="!isView" type="primary" @click="submit" size="small" icon="el-icon-check" :loading="loading">保存</el-button>
        <el-button v-if="!isView && (!form.status || form.status === 0 || form.status === 2)" type="primary" @click="submitAudit" size="small" icon="el-icon-check" :loading="loading">保存送审</el-button>

      </span>
      <table-law :dialog="TableLawVisible" ref="dataLaw" @cancelDialog="closeLawDialog"></table-law>
    </el-dialog>

    <el-dialog title="审计查询单-答复" fullscreen custom-class="ledger" :visible.sync="replyBox" :close-on-click-modal="!replyBox" :append-to-body="true" :before-close="resetForm" width="1200px" top="5vh">
      <div class="title">基本信息</div>
      <el-form ref="optForm" :model="form" label-width="90px">
        <el-row>
          <el-col :span="6">
            <el-form-item label-width="100px" label="项目编号: " prop="projectCode" >
              {{form.projectCode}}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label-width="100px" label="项目名称:" prop="projectName">
              {{form.projectName}}
            </el-form-item>
          </el-col>
            <el-col :span="6">
              <el-form-item label-width="100px" label="要求反馈时间:" prop="auditMatter">
                {{form.feedbackTime}}
              </el-form-item>
            </el-col>
        </el-row>
      </el-form>
      <div class="title">基本信息</div>
      <el-form ref="optForm" :model="form" label-width="90px">
        <el-row>
          <el-col>
            <el-form-item label-width="100px" label="查询问题:" prop="auditMatter">
              <pre class="pre-style">{{ form.auditMatter }}</pre>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title">被审计单位答复</div>
        <el-row>
          <el-col>
            <el-form-item label-width="100px" label="答复:" prop="auditPurpose">
              <el-input v-model="form.providerOpinion" placeholder="答复" type="textarea"></el-input>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label-width="100px" label="附件:">
              <el-upload
                class="upload-demo"
                action="/admin/sys-file/upload"
                :headers="{Authorization}"
                :file-list="fileList"
                :on-success="handleSuccess"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :show-file-list="true">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title">审计查询单文书</div>
        <el-row >
          <el-col :span="24">
            <el-form-item label-width="110px" label="审计查询单:" >
              <web-document :form-data="form" readWord="edit" :pageType="'engineeringEvidence'" @createWordFile="wordFileHandle" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm" size="small" icon="el-icon-close">关闭</el-button>
        <el-button v-if="!isView && form.status === 3" type="primary" @click="saveSubmit" size="small" icon="el-icon-check" :loading="loading">送审</el-button>
      </span>
    </el-dialog>

    <el-dialog title="审计查询单-审核" fullscreen custom-class="ledger" :visible.sync="auditBox" :close-on-click-modal="!auditBox" :append-to-body="true" :before-close="resetForm" width="1200px" top="5vh">
      <div class="title">基本信息</div>
      <el-form ref="optForm" :model="form" label-width="90px">
        <el-row>
          <el-col :span="6">
            <el-form-item label-width="100px" label="项目编号: " prop="projectCode" >
              {{form.projectCode}}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label-width="100px" label="项目名称:" prop="projectName">
              {{form.projectName}}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="title">基本信息</div>
      <el-form ref="optForm" :model="form" label-width="90px">
        <el-row>
          <el-col>
            <el-form-item label-width="100px" label="查询问题:" prop="auditMatter">
              <pre class="pre-style">{{ form.auditMatter }}</pre>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label-width="100px" label="要求反馈时间:" prop="auditMatter">
              {{form.feedbackTime}}
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title">被审计单位答复</div>
        <el-row>
          <el-col>
            <el-form-item label-width="100px" label="答复:" prop="auditPurpose">
              <pre class="pre-style">{{ form.providerOpinion }}</pre>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label-width="100px" label="附件:">
              <el-upload
                class="upload-demo"
                action="/admin/sys-file/upload"
                :headers="{Authorization}"
                :file-list="fileList"
                :on-preview="handlePreview"
                :show-file-list="true">
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title">审计查询单文书</div>
        <el-row >
          <el-col :span="24">
            <el-form-item label-width="110px" label="审计查询单:" prop="projectName">
              <web-document :form-data="form" readWord="view" :pageType="'engineeringEvidence'" @createWordFile="wordFileHandle" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm" size="small" icon="el-icon-close">关闭</el-button>
        <el-button v-if="form.status === 4" type="primary" @click="forward" size="small" icon="el-icon-check" :loading="loading">保存并转交审计组</el-button>
      </span>
    </el-dialog>
    <el-dialog top="5vh" :title="formTitle" :visible.sync="viewBox"
               :append-to-body="true" :before-close="closeViewBox" width="1200px">
      <EngineeringEvidenceView :params="form"></EngineeringEvidenceView>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeViewBox" size="small" icon="el-icon-close">关闭</el-button>
      </span>
    </el-dialog>

    <TaskAuditDialog :dialog="taskAuditDialog" @setValue="setTaskAuditTaskDialog" @closeDialog="closeTaskAuditTaskDialog" ref="taskAuditDialog" />
    <TaskAuditLogDialog :dialog="taskAuditLogDialog" :process-id="processId" @closeDialog="closeTaskAuditTaskLogDialog"/>
    <ChoseProject :projectDialog="projectDialog" ref="projectDataForm" @cancelDialog="closeProjectDialog" @setValue="projectDataHandle"/>

  </basic-container>
</template>

<script>
import {fetchList,submitAudit,submit,saveSubmit,forward,getEvidence, closeEvidence} from "@/api/adis/execute/evidence";
import {delObj} from "@/api/admin/file";
import {mapGetters} from "vuex";
import Tinymce from "@/components/Tinymce/index.vue";
import TaskAuditDialog from "@/components/act/TaskAuditDialog";
import TaskAuditLogDialog from "@/components/act/TaskAuditLogDialog";
import projectDialog from "@/components/audited/ChoseProject";
import TableForm from "@/components/form/projectProblem.vue";
import WebDocument from '@/components/form/webDocument.vue';
import EngineeringEvidenceView from "@/components/actForm/EngineeringEvidenceView.vue";
import ChoseProject from "@/components/audited/ChoseProject.vue";
import TableLaw from "@/components/table/lawList.vue";

export default {
  components: {
    TableLaw,
    ChoseProject,
    EngineeringEvidenceView,
    TableForm,
    projectDialog,
    Tinymce,
    TaskAuditDialog,
    TaskAuditLogDialog,
    WebDocument,
  },
  data() {
    return {
      formTitle: '',
      formBox: false,
      isEdit: false,
      isView: false,
      tableData: [],
      loading: false,
      query: {},
      form:{},
      fileForm: {},
      pointForm:{},
      fileList:[],
      newTableData:[],
      page:{
        total: 1,
        currentPage: 10
      },
      Authorization: '',
      taskAuditDialog: false,
      taskAuditLogDialog: false,
      processId : '',
      projectDialog: false,
      addOrUpdateVisible:false,
      formDisplay: false,

      replyBox: false,
      auditBox: false,
      confirmBox: false,

      viewBox: false,
      TableLawVisible: false,
    }
  },
  computed: {
    ...mapGetters(["permissions","userInfo"])
  },
  created() {
    this.onLoad(this.page);
    this.Authorization = 'Bearer ' + this.$store.getters.access_token
  },
  methods: {
    handleCellClick(row, column) {
      if (row && column.label !== "操作"){
        this.showViewBox(row)
      }
    },

    createDiscover(row){
      this.addOrUpdateVisible = true;
      this.confirmBox = false;
      this.$nextTick(() => {
        this.$refs.dataForm.init(row);
      })
    },
    closeDoubtfulDialog(){
      this.addOrUpdateVisible = false;
    },
    /**
     * 文件上传
     */
    handleSuccess(response, file, fileList){
      console.info(response);
      if (!this.fileList) {
        this.fileList = [{url: response.data.url, name: response.data.fileName}]
      } else {
        this.fileList.push({url: response.data.url, name: response.data.fileName})
      }
    },
    handleRemove(file, fileList) {
      this.fileList.forEach((item, v) => {
        if (file.url === item.url) this.fileList.splice(v, 1)
      })
    },
    handlePreview(file) {
      const a = document.createElement('a');
      let url = file.url ? file.url : file.response.data.url;
      console.log(url);      // let fileName = '你想要的文件名.docx'; // 这里设置你想要的文件名，包括扩展名
      a.setAttribute('download', file.name);
      a.setAttribute('href', url);
      a.click();
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(index) {
      let splice = this.fileList.splice(index, 1);
      delObj(splice[0].id).then(()=>{
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      })
      // return this.$confirm(`确定移除 ${ file.fileName }？`);
    },

    showProjectDialog(){
      this.projectDialog= true;
      this.$nextTick(() => {
        this.$refs.projectDataForm.initParams({
          isGCProjectApproved: true,//结算送审是否审批完成
          hasImage: true,//已被工程过程管理使用用的项目
          isEngineering: true,//是否是工程审计
          isTermination: false
        })
      })
    },
    closeProjectDialog(){
      this.projectDialog= false;
    },
    projectDataHandle(data){
      this.projectDialog= false;
      // this.pointForm = data;
      this.form = data;
      console.log(this.form);
    },
    onSearch() {
      this.page.current = 1;
      this.onLoad(this.page);
    },
    searchReset() {
      this.query = {};
      this.page.current = 1;
      this.onLoad(this.page);
    },
    currentChange(current) {
      this.page.current = current;
      this.onLoad(this.page);
    },
    sizeChange(size) {
      this.page.size = size;
      this.onLoad(this.page);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      // if(this.query.publishDates) {
      //   this.query.startDate = this.query.publishDates[0];
      //   this.query.endDate = this.query.publishDates[1];
      // }
      this.query.isEngineering = 1;
      fetchList(Object.assign(params, this.query, page)).then(res => {
        this.loading = false;
        const data = res.data.data;
        this.page.total = data.total;
        this.tableData = data.records;
      }, () => {
        this.loading = false;
      });
    },
    showViewBox(row){
      getEvidence(row.evidenceId).then((res) => {
        this.form = res.data.data;
        this.formTitle = row.projectName;
        this.viewBox = true;
      });
    },
    closeViewBox() {
      this.viewBox = false;
    },

    showEditBox(row) {
      getEvidence(row.evidenceId).then((res) => {
        this.form = res.data.data;
        this.fileList = this.form.attachments;
        this.fileList.forEach((item) =>{
          item.name = item.fileName;
          item.url = item.fileUrl;
        })
        this.formTitle = '编辑';
        this.formBox = true;
        this.isView = false;
        this.isEdit = false;
      });
    },
    resetForm() {
      this.formBox = false;
      this.viewBox = false;
      this.isEdit = false;
      this.isView = false;
      this.form = {};
      this.pointForm = {};
      this.formTitle = '';
      this.$refs['optForm'] && this.$refs['optForm'].resetFields();
      this.viewBox = false;
      this.printBox = false;
      this.fileList = [];
      this.fileForm = {};

      this.replyBox = false;
      this.auditBox = false;
      this.confirmBox = false;
    },
    createEvidence() {
      this.form = {};
      this.formTitle = '新增';
      this.formBox = true;
      this.isEdit = false;
    },
    /**提交*/
    saveSubmit(){
      this.$refs['optForm'].validate((valid) => {
        if (valid) {
          this.form.attachments = [];
          this.fileList.forEach(file => {
            this.form.attachments.push({fileName: file.name, fileUrl: file.url})
          })
          this.loading = true;
          saveSubmit(this.form).then((res) => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.resetForm();
            this.onLoad(this.page);
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    submit() {
      this.$refs['optForm'].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.fileList.forEach(file => {
            this.form.attachments.push({fileName: file.name, fileUrl: file.url})
          })
          this.form.isEngineering = 1;
          submit(this.form).then((res) => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.resetForm();
            this.onLoad(this.page);
            console.log(this.fileList);
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    /**提交审批*/
    submitAudit() {
      this.$refs['optForm'].validate((valid) => {
        if (valid) {
          this.fileList.forEach(file => {
            this.form.attachments.push({fileName: file.name, fileUrl: file.url})
          })
          this.form.isEngineering = 1;
          this.loading = true;
          submitAudit(this.form).then((res) => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.resetForm();
            this.onLoad(this.page);
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    forward() {
      this.$refs['optForm'].validate((valid) => {
        if (valid) {
          this.fileList.forEach(file => {
            this.form.attachments.push({fileName: file.name, fileUrl: file.url})
          })
          this.loading = true;
          forward(this.form).then((res) => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.resetForm();
            this.onLoad(this.page);
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    /**=========审批相关==begin===========*/
    showTaskAuditTaskDialog(row) {
      this.taskAuditDialog = true;
      this.$refs['taskAuditDialog'].initData({taskId: row.taskId, processId: row.processId});
    },
    closeTaskAuditTaskDialog() {
      this.taskAuditDialog = false;
    },
    setTaskAuditTaskDialog() {
      this.taskAuditDialog = false;
      this.onLoad(this.page);
    },
    showTaskAuditLogDialog(row) {
      this.processId = row.processId;
      this.taskAuditLogDialog = true;
    },
    closeTaskAuditTaskLogDialog() {
      this.taskAuditLogDialog = false;
    },
    /**=========审批相关==end===========*/
    downloadWord: function(row) {
      this.downBlobFile(
        "/exam/auditEvidence/downloadWord/"+ row.evidenceId,
        {},
        row.projectName + "查询单.docx"
      )
    },
    wordFileHandle(e) {
      console.log(e,123456789);
      this.$set(this.form, "wordFile", e.wordFile);
      this.$set(this.form, "evidenceId", e.id);
      console.log(this.form,12313132131313);
    },

    showReplyBox(row) {
      getEvidence(row.evidenceId).then((res) => {
        this.form = res.data.data;
        this.fileList = this.form.attachments;
        this.fileList.forEach((item) =>{
          item.name = item.fileName;
          item.url = item.fileUrl;
        })
        this.replyBox = true;
      });
    },

    showAuditBox(row) {
      getEvidence(row.evidenceId).then((res) => {
        this.form = res.data.data;
        this.fileList = this.form.attachments;
        this.fileList.forEach((item) =>{
          item.name = item.fileName;
          item.url = item.fileUrl;
        })
        this.auditBox = true;
      });
    },

    showConfirmBox(row) {
      getEvidence(row.evidenceId).then((res) => {
        this.form = res.data.data;
        this.fileList = this.form.attachments;
        this.fileList.forEach((item) =>{
          item.name = item.fileName;
          item.url = item.fileUrl;
        })
        this.confirmBox = true;
      });
    },

    handleCloseEvidence() {
      this.$refs['optForm'].validate((valid) => {
        if (valid) {
          this.fileList.forEach(file => {
            this.form.attachments.push({fileName: file.name, fileUrl: file.url})
          })
          this.loading = true;
          closeEvidence(this.form).then((res) => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.resetForm();
            this.onLoad(this.page);
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    openLawFunction() {
      this.TableLawVisible = true;
    },
    closeLawDialog(val) {
      if (val) this.$set(this.form, 'lawContent', val)
      this.TableLawVisible = false;
    }
  }
}
</script>

<style>
</style>
